@echo off
setlocal enabledelayedexpansion

if "%~1"=="" (
    echo Usage: kill-port.bat [port]
    echo Example: kill-port.bat 7001
    pause
    exit /b 1
)

set PORT=%1
echo Killing processes on port %PORT%...

for /f "tokens=5" %%a in ('netstat -ano ^| findstr ":%PORT% "') do (
    set PID=%%a
    echo Killing process !PID!...
    
    :: 检查进程是否存在
    tasklist /FI "PID eq !PID!" 2>nul | find /i "!PID!" >nul
    if !errorlevel! equ 0 (
        taskkill /PID !PID! /F >nul 2>&1
        if !errorlevel! equ 0 (
            echo Process !PID! killed successfully
        ) else (
            echo Failed to kill process !PID! - may need admin rights
        )
    ) else (
        echo Process !PID! not found or already terminated
    )
)

echo Done!
pause